<?php

namespace App\Models\User;

use App\Helpers\SelfEncrypt;
use App\Models\BaseModel;
use App\Models\Shop\OrderPaymentModel;
use Frontend\Models\UserBaseModel;

class RechargeRecordModel extends BaseModel
{
    protected $table = 'recharge_record';

    protected $primaryKey = 'id';

    public $dateFormat = 'U';

    protected $dates = [
        'created_at',
        'updated_at',
        'handled_at',
    ];

    public function user()
    {
        return $this->belongsTo('DC\UserCenter\Models\UserBaseModel','user_id','member_id');
    }

    public function apply($data)
    {
        $user_id = request()->input('user_id');
        $money = $data['money'];
        $user = UserBaseModel::find($user_id);
        if(!$user){
            $this->errorMsg = '会员信息不存在';
            return false;
        }

        $service_fee = 0 ;
        if(get_rule('rg_tax') >0 && get_rule('rg_tax') <100){
            $service_fee =  $money * get_rule('rg_tax') * 0.01;
        }

        $this->rg_sn = SelfEncrypt::createCode('rg');
        $this->user_id = $user_id;
        $this->currency_id = $data['pay_type'];
        $this->rg_type = 2;
        $this->money = $money-$service_fee;;
        $this->service_fee = $service_fee;
        $this->voucher = $data['voucher'] ?? '';
        $this->from_account = '';
        $this->to_account = json_encode($this->handleToAccount());
        $this->from_phone = $user->user_phone;
        $this->from_remark = $data['remark'] ?? '';

        if($this->save()){
            $orderPayment = new OrderPaymentModel();
            $orderPayment->createPayment(0,  $this->rg_sn , '', "在线支付订单", $money, 2, $this->id);
            return $this->id;
        }
        return false;
    }

    private function handleToAccount()
    {
        $accounts = array_map(function ($val){
            return str2arr($val,'-');
        },config('website.company_account'));
        $default = array_shift($accounts);

        $account['类型'] = $default[2];
        $account['账号'] = $default[1];
        return $account;
    }
}
